package com.example.mybatisplusgenerator;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.example.mybatisplusgenerator.qqq.dto.ParseOrderDto;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.security.MessageDigest;

/**
 * @Description TODO
 * @Author fanhailong
 * @Date 2022/5/11 16:55
 */
@Slf4j
public class GyUtil {

    public static void main(String[] args) {
        JSONObject params = new JSONObject();
        params.put("appkey", "183158");
        params.put("sessionkey", "2cd00a0868aa4506ad9f386b9052819c");
        params.put("page_no", 1);
        params.put("page_size", 10);
        params.put("method", "gy.erp.trade.history.get");
//        params.put("date_type", 1);
//        params.put("has_cancel_data", false);
//        params.put("detail_flag", true);
//        params.put("start_delivery_date", "2022-03-21 00:00:00");
//        params.put("end_delivery_date", "2022-03-22 00:00:00");
        String str = params.toJSONString();
        String secret = "2e01f689b14848ac88884a72a042fe84";
        params.put("sign", sign(str, secret));
        String s = sendPost("http://v2.api.guanyierp.com/rest/erp_open", params.toJSONString());
        JSONObject repsonse = JSON.parseObject(s);
        JSONArray orders = JSON.parseArray(repsonse.get("orders").toString());
        for (Object orderObj : orders) {
            ParseOrderDto orderDto = JSON.parseObject(orderObj.toString(), ParseOrderDto.class);
            System.out.println(orderDto);
        }
    }

    public static String sign(String str, String secret) {
        log.info("source:   " + str);
        log.info("secret:   " + secret);
        StringBuilder enValue = new StringBuilder();
        enValue.append(secret);
        enValue.append(str);
        enValue.append(secret);
        log.info("append   secret: " + enValue.toString());
        log.info("sign:   " + encryptByMD5(enValue.toString()));
        return encryptByMD5(enValue.toString());
    }

    private static String encryptByMD5(String data) {
        StringBuilder sign = new StringBuilder();
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] bytes = md.digest(data.getBytes("UTF-8"));
            for (int i = 0; i < bytes.length; i++) {
                String hex = Integer.toHexString(bytes[i] & 0xFF);
                if (hex.length() == 1) {
                    sign.append("0");
                }
                sign.append(hex.toUpperCase());
            }
        } catch (Exception e) {
            log.error("管易接口调用失败, 签名异常, data:{}", data, e);
        }
        return sign.toString();
    }

    public static String sendPost(String url, String data) {
        log.info("url:   " + url);
        log.info("request:   " + data);
        try {
            CloseableHttpClient httpclient = null;
            CloseableHttpResponse httpresponse = null;
            try {
                httpclient = HttpClients.createDefault();
                HttpPost httppost = new HttpPost(url);
                StringEntity stringentity = new StringEntity(data, ContentType.create("text/json", "UTF-8"));
                httppost.setEntity(stringentity);
                httpresponse = httpclient.execute(httppost);
                String response = EntityUtils.toString(httpresponse.getEntity());
                log.info("response:   " + response);
                return response;
            } finally {
                if (httpclient != null) {
                    httpclient.close();
                }
                if (httpresponse != null) {
                    httpresponse.close();
                }
            }
        } catch (Exception e) {
            log.error("管易接口调用异常，url:{}, data:{}", url, data, e);
        }
        return null;
    }

}
